<template>
   <div>
      <Category :scene="scene"></Category>
      <div v-show="scene===0">
         <el-card shadow="hover" :body-style="{ padding: '20px' }" style="margin-top: 10px">
            <el-button type="primary" :icon="Plus" @click="addAttr" :disabled="!CategoryStore.c3Id">添加属性</el-button>
            <el-table border stripe style="margin-top: 10px" :data="attrList">
               <el-table-column label="序号" width="80px" type="index"></el-table-column>
               <el-table-column label="属性名称" width="130px" prop="attrName"></el-table-column>
               <el-table-column label="属性值列表">
                  <template #="{row,$index}">
                     <el-tag style="margin:0px 3px" class="ml-2" type="success"
                        v-for="(attrVal,index) in row.attrValueList" :key="attrVal.id">{{ attrVal.valueName
                        }}</el-tag>
                  </template>
               </el-table-column>
               <el-table-column label="操作" width="130px">
                  <template #="{ row ,$index}">
                     <el-button type="warning" size="small" :icon="Edit" @click="updateAttr(row)" />
                     <el-button type="danger" size="small" :icon="Delete" @click="removeAttr(row)"></el-button>
                  </template>
               </el-table-column>
            </el-table>
         </el-card>
      </div>
      <div v-show="scene==1">
         <el-card shadow="hover" :body-style="{ padding: '20px' }">
            <el-form label-width="80px" :inline="true">
               <el-form-item label="属性名">
                  <el-input placeholder="请输入属性名字" clearable v-model="attrParams.attrName"></el-input>
               </el-form-item>
            </el-form>
            <el-button type="primary" size="default" :icon="Plus" @click="addAttrValue"
               :disabled="attrParams.attrName ? false : true">添加属性值</el-button>
            <el-button size="default" @click="scene=0">取消</el-button>
            <el-table border stripe style="margin:10px 0px" :data="attrParams.attrValueList">
               <el-table-column label="序号" type="index">
               </el-table-column>
               <el-table-column label="属性值名称">
                  <template #="{row,$index}">
                     <el-input :ref="(vc) =>(inputArr[$index] = vc)" v-if="row.flag" v-model="row.valueName" clearable
                        @blur="toLook(row,$index)"></el-input>
                     <div v-else @click="toEdit(row,$index)">{{row.valueName}}</div>
                  </template>
               </el-table-column>
               <el-table-column label="操作">

                  <template #="{row ,$index}">
                     <el-button type="danger" size="small" :icon="Delete" @click="a(row,$index)"></el-button>
                  </template>
               </el-table-column>
            </el-table>
            <el-button type="primary" size="default" @click="save"
               :disabled="attrParams.attrValueList.length > 0 ? false : true">保存</el-button>
            <el-button size="default" @click="scene=0">取消</el-button>
         </el-card>
      </div>
   </div>
</template>

<script setup lang="ts">
import {
   Check,
   Delete,
   Edit,
   Message,
   Search,
   Star,
   Plus
} from '@element-plus/icons-vue'
import { ref, watch, reactive, nextTick } from 'vue'
import categoryStore from '@/stores/category'
import { ElMessage } from "element-plus";
import { reqAttrList, reqAddorUpdatartte, reqDeleteAttr } from '@/api/product/attr/attr'
//引入lodash里面cloneDepp---深拷贝
import _ from "lodash";
//引入数据类型
import type {attrResponseData,attrModel,attrValueModel} from '../../../api/product/attr/model/attr'
let CategoryStore = categoryStore()
// 存储平台属性
let attrList = ref<attrResponseData>([])
// 添加属性值按钮的切换
let scene = ref<number>(0)
//定义数组ref类型数据，将来存储el-input组件的实例
let inputArr = ref<any>([]);
// 需要添加或修改的参数
let attrParams = reactive<attrModel>({
   attrName: '',
   categoryId: '',
   categoryLevel: 3,
   attrValueList: []
})

watch(() => CategoryStore.c3Id, () => {
   if (CategoryStore.c3Id == '') return
   getAttrList()

})
const getAttrList = async () => {
   let result:attrResponseData= await reqAttrList(CategoryStore.c1Id, CategoryStore.c2Id, CategoryStore.c3Id)
   // console.log(result);
   attrList.value = result

}
// 添加属性按钮
const addAttr = () => {
   scene.value = 1

   //点击添加属性按钮每一次都要情况带给服务器参数
   //情况数据:浅拷贝
   Object.assign(attrParams, {
      attrName: "",
      categoryId: CategoryStore.c3Id, //每一次进入到添加|修改属性的时候，清空数据|同时把三级分类ID收集到
      categoryLevel: 3,
      attrValueList: [],
   });
}
// 添加属性值按钮
const addAttrValue = () => {
   attrParams.attrValueList.push({
      valueName: '',
      flag: true
   })
   //获取el-input组件实例,数组最后这个元素
   nextTick(() => {
      inputArr.value[attrParams.attrValueList.length - 1].focus();
   });
}
// 属性值表单失去光标时，flag改为false
const toLook = (row:attrValueModel, $index:number) => {
   // 如果添加的是空值则取消
   if (row.valueName.trim() == '') {
      ElMessage({
         type: "warning",
         message: "亲爱的属性值不能为空",
      });
      //属性值数组把当前非法属性值对象干掉
      attrParams.attrValueList.splice($index, 1);
      //代表后面代码不能执行
      return;
   }
   let repeat = attrParams.attrValueList.find((item) => {
      if (row != item) {
         return row.valueName === item.valueName
      }
   })
   if (repeat) {
      ElMessage({
         type: "warning",
         message: "亲爱的属性值不能重复",
      });
      //属性值数组把当前非法属性值对象干掉
      attrParams.attrValueList.splice($index, 1);
   }
   row.flag = false
}
// 点击时切换为修改状态，flag改为true
const toEdit = (row:attrValueModel, $index:number) => {
   row.flag = true
   //点击div切换显示el-input，需要聚焦
   nextTick(() => {
      inputArr.value[$index].focus();
   });
}

const save = async () => {
   //参数整理一下:属性值的数组flag属性不需要--->干掉
   attrParams.attrValueList.forEach((item) => {
      if (item.hasOwnProperty("flag")) {
         //删除某一个属性
         delete item.flag;
      }
   });
   //  attrParams.attrValueList =  attrParams.attrValueList.map((item)=>{
   //      return {
   //        valueName:item.valueName
   //      }
   //  })
   try {
      //添加属性成功
      await reqAddorUpdatartte(attrParams);
      //切换场景
      scene.value = 0;
      //提示
      ElMessage({
         type: "success",
         message: attrParams.id ? "修改成功" : "添加成功",
      });
      //获取全部最新的属性的数据
      getAttrList();
   } catch (error) {
      ElMessage({
         type: "success",
         message: attrParams.id ? "修改失败" : "添加失败",
      });
   }
};
const a = (row: any, $index: any) => {
   attrParams.attrValueList.splice($index, 1)
}
// 修改属性按钮
const updateAttr = (row:attrModel) => {
   scene.value = 1
   // 深拷贝一份文件给修改页面
   Object.assign(attrParams, _.cloneDeep(row))
}
const removeAttr = async (row:attrModel) => {
   try {
      await reqDeleteAttr(row.id)
      ElMessage({
         type: "success",
         message: `删除${row.attrName}成功`,
         duration:500
      });
      getAttrList()
   } catch (error) {
      ElMessage({
         type: "error",
         message: `删除${row.attrName}失败`,
      });
   }
}
</script>

<style scoped>

</style>